package com.joymart.qualification.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.joymart.common.system.IdGenerator;
import com.joymart.qualification.model.AdvanceEvaluation;
import com.joymart.qualification.model.AdvanceEvaluationRecord;
import com.joymart.user.model.BusinessRole;
import com.joymart.user.service.UserCacheManager;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class AdvanceEvaluationPersistingService {

    @Autowired
    private IdGenerator idGenerator;
    @Autowired
    private UserCacheManager userCacheManager;
    @Autowired
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
    @Autowired
    private ObjectMapper objectMapper;

    @SneakyThrows
    public void save(AdvanceEvaluation advanceEvaluation) {
        advanceEvaluation.setId(idGenerator.next());
        String sql =  " insert into advance_evaluation_record (id," +
                " user_id, " +
                " target_role, "+
                " range_start, " +
                " range_end, " +
                " content," +
                " passed," +
                " created_at) values (:id, " +
                " :userId," +
                " :targetRole," +
                " :rangeStart," +
                " :rangeEnd," +
                " :content::jsonb," +
                " :passed," +
                " :createdAt)";
        namedParameterJdbcTemplate.update(sql, Map.of(
                "id", advanceEvaluation.getId(),
                "targetRole", advanceEvaluation.getTargetRole().name(),
                "userId", advanceEvaluation.getUserId(),
                "rangeStart", advanceEvaluation.getRange().getStart(),
                "rangeEnd", advanceEvaluation.getRange().getEnd(),
                "content", objectMapper.writeValueAsString(advanceEvaluation),
                "passed", advanceEvaluation.isPassed(),
                "createdAt", advanceEvaluation.getCreatedAt()
        ));
    }


    @SneakyThrows
    public AdvanceEvaluationRecord getEvaluationResultById(String id) {
        String sql = "select content from advance_evaluation_record where id = :id";
        String rs = namedParameterJdbcTemplate.queryForObject(sql, Map.of("id", id), String.class);
        return objectMapper.readValue(rs, AdvanceEvaluationRecord.class);
    }

    @SneakyThrows
    public AdvanceEvaluationRecord getLatestEvaluationResult(String userId, BusinessRole targetRole) {

        String existSql = """
                      SELECT MAX(id)
                      FROM advance_evaluation_record
                      WHERE user_id = :userId
                        AND target_role = :targetRole
                """;
        String id = namedParameterJdbcTemplate.queryForObject(existSql, Map.of("userId", userId, "targetRole", targetRole.name()), String.class);
        if(id == null){
            return null;
        }
        return this.getEvaluationResultById(id);
    }
}
